<?php

namespace app\admin\controller\pt;

use app\common\controller\Backend;
use think\Db;

/**
 * 组长管理
 *
 * @icon fa fa-users
 */
class Leader extends Backend
{
    protected $excludeFields = ['update_time'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 组长列表 - 用于selectpage
     */
    public function index()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $list = Db::name('admin')
            ->alias('a')                              // 给 admin 表起别名 a
            ->join('auth_group_access aga', 'a.id = aga.uid')   // 使用 a.id
            ->join('auth_group ag', 'ag.id = aga.group_id')     // 使用 ag.id
            ->where($where)
            ->where('ag.name', '组长')             // 按角色组名称过滤
            ->where('a.status', 'normal')             // 状态为 normal
            ->field('a.id,a.nickname,a.username,a.email,a.mobile')
            ->order($sort, $order)
            ->paginate($limit);

        $result = ['total' => $list->total(), 'rows' => $list->items()];

        return json($result);

    }

    /**
     * Selectpage 方法 - 专门处理组长选择
     */
    protected function selectpage()
    {
        // 设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        // 搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array) $this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array) $this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array) $this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array) $this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);

        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }

        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'nickname';

        // 直接查询组长用户ID，通过JOIN确保只获取组长组的用户
        $leaderIds = Db::name('admin')
            ->alias('a')
            ->join('auth_group_access aga', 'a.id = aga.uid')
            ->join('auth_group ag', 'ag.id = aga.group_id')
            ->where('ag.name', '组长')
            ->where('a.status', 'normal')
            ->column('a.id');

        if (empty($leaderIds)) {
            return json(['list' => [], 'total' => 0]);
        }


        // 构建基础查询
        $baseQuery = Db::name('admin')
            ->where('id', 'in', $leaderIds)
            ->where('status', 'normal');

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $primaryvalue = is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue);
            $baseQuery->where($primarykey, 'in', $primaryvalue);
            $pagesize = 999999;
        } else {
            // 添加搜索条件
            if (!empty($word)) {
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $searchValue = reset($word);
                    $baseQuery->where(function ($query) use ($searchValue, $searchfield) {
                        foreach ($searchfield as $fieldName) {
                            $query->whereOr($fieldName, 'like', '%' . $searchValue . '%');
                        }
                    });
                } else {
                    $baseQuery->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $item) {
                            $query->whereOr(function ($subQuery) use ($item, $searchfield) {
                                foreach ($searchfield as $fieldName) {
                                    $subQuery->whereOr($fieldName, 'like', '%' . $item . '%');
                                }
                            });
                        }
                    });
                }
            }
        }

        // 查询总数
        $total = $baseQuery->count();
        $list = [];

        if ($total > 0) {
            // 重新构建查询对象，避免修改原有的查询条件
            $dataQuery = Db::name('admin')
                ->where('id', 'in', $leaderIds)
                ->where('status', 'normal');

            // 重新应用搜索条件
            if ($primaryvalue !== null) {
                $primaryvalue = is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue);
                $dataQuery->where($primarykey, 'in', $primaryvalue);
            } else {
                if (!empty($word)) {
                    $word = array_filter(array_unique($word));
                    if (count($word) == 1) {
                        $searchValue = reset($word);
                        $dataQuery->where(function ($query) use ($searchValue, $searchfield) {
                            foreach ($searchfield as $fieldName) {
                                $query->whereOr($fieldName, 'like', '%' . $searchValue . '%');
                            }
                        });
                    } else {
                        $dataQuery->where(function ($query) use ($word, $searchfield) {
                            foreach ($word as $item) {
                                $query->whereOr(function ($subQuery) use ($item, $searchfield) {
                                    foreach ($searchfield as $fieldName) {
                                        $subQuery->whereOr($fieldName, 'like', '%' . $item . '%');
                                    }
                                });
                            }
                        });
                    }
                }
            }

            // 设置排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);
                $primaryvalue = implode(',', $primaryvalue);
                $dataQuery->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                if (!empty($order)) {
                    foreach ($order as $orderField => $orderDirection) {
                        $dataQuery->order($orderField, $orderDirection);
                    }
                } else {
                    $dataQuery->order('id', 'asc');
                }
            }

            // 查询数据
            $datalist = $dataQuery
                ->field('id, username, nickname, mobile, email')
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                $result = [
                    $primarykey => $item[$primarykey] ?? '',
                    $field => $item[$field] ?? '',
                ];
                $result['pid'] = 0;
                $result = array_map("htmlentities", $result);
                $list[] = $result;
            }
        }

        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

}
